package com.zys.hotel_management.controller;


import com.zys.hotel_management.common.Response;
import com.zys.hotel_management.entity.Customer;
import com.zys.hotel_management.entity.dto.LoginDTO;
import com.zys.hotel_management.service.CustomerService;
import com.zys.hotel_management.utils.JwtUtils;
import com.zys.hotel_management.utils.UserContext;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/customers")
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @PostMapping("/register")
    public Response<Void> register(@RequestBody Customer customer) {
        try {
            customerService.register(customer);
            return Response.success(null);
        } catch (Exception e) {
            return Response.fail(500, "注册失败: " + e.getMessage());
        }
    }

    @PostMapping("/login")
    public Response<String> login(@RequestBody LoginDTO loginDTO) {
        Customer customer = customerService.login(loginDTO.getUsername(), loginDTO.getPassword());
        if (customer != null) {
            String jwtToken = JwtUtils.generateToken(customer.getUsername());
            return Response.success(jwtToken);
        } else {
            return Response.fail(401, "用户名或密码错误");
        }
    }

    @GetMapping
    public Response<Customer> getCustomerInfo() {
        Customer customer = UserContext.getUser();
        if (customer != null) {
            return Response.success(customer);
        } else {
            return Response.fail(404, "未找到对应客户信息");
        }
    }

    @GetMapping("/{id}")
    public Response<Customer> getById(@PathVariable Integer id) {
        Customer customer = customerService.getById(id);
        if (customer != null) {
            return Response.success(customer);
        } else {
            return Response.fail(404, "未找到对应客户信息");
        }
    }
}